import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  message,
  Divider,
  Popconfirm,
  Upload,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { ruleP, nameMaxLength,nameMinLength, remarkMaxLength } from '@/utils/rule';
import styles from '../search.less';
import BindFields from './BindFields';
const { TextArea } = Input;
const FormItem = Form.Item;

const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text);
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑类别' : '新增类别'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="类别代码">
        {form.getFieldDecorator('typeCode', {
          rules: [
            { required: true, whitespace: true, message: '类别代码不能为空' },
            { max: nameMaxLength()[0], message: nameMaxLength()[1] },
            { pattern: new RegExp(ruleP(1)[0], 'g'), message: ruleP(1)[1] },           
          ],
          initialValue: (text && text.typeCode) || '',
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="类别名称">
        {form.getFieldDecorator('typeName', {
          rules: [
            { required: true, whitespace: true, message: '类别名称不能为空' },
            {min: nameMinLength()[0], message: nameMinLength()[1] },
            { max: nameMaxLength()[0], message: nameMaxLength()[1] },           
          ],
          initialValue: (text && text.typeName) || '',
        })(<Input placeholder="请输入" />)}
      </FormItem>

      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="备注">
        {form.getFieldDecorator('remark', {
          rules: [{ max: remarkMaxLength()[0], message: remarkMaxLength()[1] }],
          initialValue: (text && text.remark) || '',
        })(<TextArea style={{ minHeight: 32 }} rows={2} />)}
      </FormItem>
    </Modal>
  );
});

const CreateSubTypeForm = Form.create()(props => {
  const { subTypeModalVisible, form, handleSubType, handleSubTypeModalVisible, text } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleSubType(fieldsValue, text);
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={'新增子类别'}
      visible={subTypeModalVisible}
      onOk={okHandle}
      onCancel={() => handleSubTypeModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="类别名称">
        {text.typeCode}-{text.typeName}-{text.typeId}
      </FormItem>

      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="子类别代码">
        {form.getFieldDecorator('typeCode', {
          rules: [
            { required: true, whitespace: true, message: '子类别代码不能为空' },
            { max: nameMaxLength()[0], message: nameMaxLength()[1] },
            { pattern: new RegExp(ruleP(1)[0], 'g'), message: ruleP(1)[1] },           
          ],
          initialValue: '',
        })(<Input placeholder="请输入" />)}
      </FormItem>

      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="子类别名称">
        {form.getFieldDecorator('typeName', {
          rules: [
            { required: true, whitespace: true, message: '子类别名称不能为空' },
            {min: nameMinLength()[0], message: nameMinLength()[1] },
            { max: nameMaxLength()[0], message: nameMaxLength()[1] },            
          ],
          initialValue: '',
        })(<Input placeholder="请输入" />)}
      </FormItem>

      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label="备注">
        {form.getFieldDecorator('remark', {
          rules: [{ max: remarkMaxLength()[0], message: remarkMaxLength()[1] }],
          initialValue: '',
        })(<TextArea style={{ minHeight: 32 }} rows={2} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ dataType, loading }) => ({
  dataType,
  loading: loading.models.dataType,
}))
@Form.create()
class dataType extends PureComponent {
  state = {
    modalVisible: false,
    subTypeModalVisible: false,
    bindFieldsVisible: false,
    expandForm: false,
    formValues: {},
    selectedRows: [],
    stepFormValues: {},
    text: {},
  };

  columns = [
    {
      title: '代码',
      dataIndex: 'typeCode',
      key: 'typeCode',
    },
    {
      title: '类别名称',
      dataIndex: 'typeName',
      key: 'typeName',
    },
    {
      title: '绑定敏感字段',
      dataIndex: 'boundField',
      key: 'boundField',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis:true,
      width:'30%',
    },

    {
      title: '操作',
      width: 300,
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleSubTypeModalVisible(true, text)}>新增子类别</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleBindFieldsModalVisible(true, text)}>绑定敏感字段</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          {text.boundField || text.children ? (
            ''
          ) : (
            <Fragment>
              <Divider type="vertical" />
              <a onClick={() => this.deleteData(text.typeId)}>删除</a>
            </Fragment>
          )}
        </Fragment>
      ),
    },
  ];

  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  // 删除方法
  handleDeleteData(typeId) {
    const { dispatch } = this.props;
    const values = {
      typeId,
    };

    dispatch({
      type: 'dataType/remove',
      payload: values,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          this.setState({ selectedRows: [] });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  }

  // 分页查询列表
  pageList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'dataType/queryList',
    });
  }

  componentDidMount() {
    this.pageList();
  }
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
    });
  };

  // 新增子类别
  handleSubTypeModalVisible = (flag, text) => {
    this.setState({
      subTypeModalVisible: !!flag,
      text: text,
    });
  };

  // 绑定敏感字段
  handleBindFieldsModalVisible = (flag, text) => {
    this.setState({
      bindFieldsVisible: !!flag,
      text: text,
    });
  };

  // 新增导入的显示和隐藏
  handleUploadVisible = flag => {
    this.setState({
      uploadVisible: !!flag,
    });
  };

  // 更新接口
  updateFn = (fields, text) => {
    const { dispatch } = this.props;
    const params = {
      typeId: text.typeId,
      typeCode: fields.typeCode,
      typeName: fields.typeName,
      remark: fields.remark,
    };
    dispatch({
      type: 'dataType/update',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = fields => {
    const { dispatch } = this.props;
    const params = {
      typeCode: fields.typeCode,
      typeName: fields.typeName,
      parentTypeId: 0,
      typeLevel: 1,
      remark: fields.remark,
    };
    dispatch({
      type: 'dataType/add',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    this.handleModalVisible();
  };

  // 新增子类别接口
  handleSubType = (fields, text) => {
    const { dispatch } = this.props;
    const params = {
      typeCode: fields.typeCode,
      typeName: fields.typeName,
      parentTypeId: text.typeId,
      remark: fields.remark,
    };
    dispatch({
      type: 'dataType/add',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
    this.handleSubTypeModalVisible();
  };

  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  render() {
    const {
      dataType: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, subTypeModalVisible, bindFieldsVisible, text } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
    };

    const subTypeMethods = {
      handleSubTypeModalVisible: this.handleSubTypeModalVisible,
      handleSubType: this.handleSubType,
    };

    const bindFieldsMethods = {
      pageList: () => this.pageList(),
      handleBindFieldsModalVisible: this.handleBindFieldsModalVisible,
    };

    return (
      <PageHeaderWrapper title="数据分类管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增一级分类
              </Button>
            </div>
            <TableList
              defaultExpandAllRows
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              pagination={false}
              // onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.typeId}
              hideRowSelection
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text} />
        {subTypeModalVisible ? (
          <CreateSubTypeForm
            {...subTypeMethods}
            subTypeModalVisible={subTypeModalVisible}
            text={text}
          />
        ) : null}
        {bindFieldsVisible ? (
          <BindFields {...bindFieldsMethods} bindFieldsVisible={bindFieldsVisible} text={text} />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default dataType;
